#-*- encoding:utf-8 -*-

from WebSite import __metaclass__
from getpass import getpass
import requests
import bs4
import re

def bs4_wrapper(func):
    def wrapped_func(*args, **kwargs):
        return bs4.BeautifulSoup(func(*args, **kwargs),"html.parser")
    return wrapped_func

class Gitee(object):
	home_url = "https://gitee.com"
	login_url = "/login"
	def __init__(self, username=None, password=None):
		if not username or not password:
			self.set_username()
			self.set_password()
		self.username = username
		self.password = password
		self.islogined = False
		self.session = requests.session()
	@bs4_wrapper
	def open(self, url="/", data=None, headers={}):
		headers = {
    	'Origin': 'https://gitee.com',
    	'Accept-Encoding': 'gzip, deflate, br',
    	'Accept-Language': 'zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7',
    	'Upgrade-Insecure-Requests': '1',
    	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    	'Content-Type': 'application/x-www-form-urlencoded',
    	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    	'Cache-Control': 'max-age=0',
    	'Referer': '',
	    'Connection': 'keep-alive',
}
		self.session.headers.update(headers)
		url = self.home_url +url
		print url
		if not data:
			return self.session.get(url).text
		else:
			return self.session.post(url, data=data).text
	def login(self):
		if self.islogined:
			raise Exception("已经是登陆状态")
		authenticity_token = self.get_auth_token(self.login_url)
		data = {
		"user[login]": self.username,
		"user[password]": self.password,
		"user[remember_me]": 0,
		"authenticity_token": authenticity_token
		}
		res = self.open(self.login_url, data)
		try:
			self.nick_name, self.home_page =re.search(u'动态 - (.*) \((.*)\) - 码云 Gitee.com', res.title.text).groups()
			self.home_page = "/"+self.home_page
			self.islogined = True
			self.user_id = self.get_user_id()
			return {"nickname":self.nick_name,
                    "username":self.username,
                   	"homepage":self.home_page,
                    "userid":int(self.user_id)
                    }
		except Exception,e:
			print e.message.encode("utf-8")
			self.islogined = False
			print "\033[31m账号或密码错误\033[0m"
			self.set_username()
			self.set_password()
			return self.login()
	def show_all_sshkeys(self):
		url = "/profile/sshkeys"
		return self.open(url)
	def push_sshkey(self, title, sshkey):
		sshkey = sshkey.strip("\n")+"\\r\\n"
		if not self.islogined:raise Exception("还没有登陆")
		url = "/profile/sshkeys"
		token = self.get_auth_token(url)
		data = {
		"utf8": "\u2713",
        "act": "key-add",
        "user_id": self.user_id,
		"authenticity_token": token,
		"commit": u"\u786e\u5b9a",
		"key[title]": title,
		"key[key]": sshkey
		}
		url = self.home_page+"/pwdauth"
		print self.open(url, data).title
		data = {
		"utf8": "\u2713",
        "act": "key-add",
        "user_id": self.user_id,
        "authenticity_token": token,
        "from": "",
		"password": self.password,
		"commit": u"\u786e\u5b9a",
		"info": '{"title":"%s","key":"%s"}'%(title, sshkey)
        }
		print data
		url = self.home_page+"/pwdauth/send"
		return self.open(url, data, headers={"Referer":self.home_url+"/profile/sshkeys"})
	def get_auth_token(self, url):
		token = None
		res = self.open(url)
		for i in res.find_all("input"):
			if i.get("name")=="authenticity_token":
				token = i.get("value")
		if token:return token
		else:raise Exception("获取token失败")
	def get_user_id(self):
		if not self.islogined:
			raise Exception("没有登陆")
		userid = None
		res = self.open("/profile/")
		print res.title
		for i in res.find_all("form"):
			if i.get("action")=="/profile":
				userid = i.get("id")[10:]
		if userid:return userid
		else:raise Exception(u"获取user_id出错")
	def set_username(self):
		self.username = raw_input("username:")
	def set_password(self):
		self.password = getpass("password:")
